import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import '../models/song.dart';

class DownloadManager {
  static const String baseUrl = 'http://www.qeecc.com';

  static final Map<String, String> _browserHeaders = {
    'User-Agent':
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
    'Accept':
        'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Connection': 'keep-alive',
    'Cache-Control': 'max-age=0',
  };

  static Future<(String?, String?)> downloadSongAndLyrics(
      Song song, Database db) async {
    try {
      // 1. 搜索歌曲获取ID
      final searchUrl = Uri.parse(
          '$baseUrl/so/${Uri.encodeComponent("${song.artist} - ${song.title}")}.html');
      final response = await http.get(
        searchUrl,
        headers: {
          ..._browserHeaders,
          'Referer': baseUrl,
        },
      );

      // 使用正则表达式匹配第一个歌曲链接
      final regex = RegExp(r'/song/([a-zA-Z0-9]+)\.html');
      final match = regex.firstMatch(response.body);

      if (match == null) {
        throw Exception('未找到歌曲: $searchUrl');
      }

      final songId = match.group(1);
      final songUrl = '$baseUrl/song/$songId.html';

      // 2. 获取下载链接
      final playUrl = Uri.parse('$baseUrl/js/play.php');
      final playResponse = await http.post(
        playUrl,
        headers: {
          ..._browserHeaders,
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
          'X-Requested-With': 'XMLHttpRequest',
          'Origin': baseUrl,
          'Referer': songUrl,
        },
        body: {
          'id': songId,
          'type': 'music',
        },
      );

      final jsonResponse = json.decode(playResponse.body);
      final mp3Url = jsonResponse['url'];

      if (mp3Url == null) {
        throw Exception('获取下载链接失败');
      }

      // 3. 下载歌词
      final lyricsUrl =
          Uri.parse('$baseUrl/plug/down.php?ac=music&lk=lrc&id=$songId');
      final lyricsResponse = await http.get(
        lyricsUrl,
        headers: {
          ..._browserHeaders,
          'Referer': songUrl,
        },
      );
      final lyrics = utf8.decode(lyricsResponse.bodyBytes);

      // 4. 下载MP3文件
      final mp3Response = await http.get(
        Uri.parse(mp3Url),
        headers: {
          ..._browserHeaders,
          'Referer': songUrl,
        },
      );

      // 5. 保存MP3到本地
      final dir = await getApplicationDocumentsDirectory();
      final musicDir = Directory('${dir.path}/music');
      await musicDir.create(recursive: true);
      final file = File('${musicDir.path}/${song.songId}.mp3');
      await file.writeAsBytes(mp3Response.bodyBytes);

      return (file.path, lyrics);
    } catch (e) {
      print('下载失败: $e');
      return (null, null);
    }
  }
}
